﻿/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef UCOP_UTIL_APPLICATION_H_
#define UCOP_UTIL_APPLICATION_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <ctime>
#include "Ucop/Typedefs.h"
#include "Ucop/Macros.h"
#include "Ucop/AtExit.h"
#include "Ucop/Util/OptionSet.h"


namespace Ucop {
namespace Util {

    class Application
    {
    public:
        enum ExitCode
        {
            EXIT_OK = 0,
            EXIT_USAGE = 64,
            EXIT_CONFIG = 65,
            EXIT_MEMORY = 66,
            EXIT_SUBSYSTEM = 67,
            EXIT_LOG = 68,
            EXIT_SOFTWARE = 70,
        };

        Application(const Char* _AppName = _L("Application"));
        virtual ~Application(void);

        int Run(int _Argc, Char* _Argv[]);
        bool HookSignal(int _Signal, bool _Ignore = false);
        void UnhookSignal(int _Signal);

        time_t GetUpTime(void) const { return _MyupTime; }

        static Application* instance(void);

    protected:
        virtual void OnDefineOptions(OptionSet& _Options);
        virtual int OnOption(const String& _Name, const String& _Arg);
        virtual int OnInitialize(void) = 0;
        virtual void OnSignal(int _Signal);
        virtual int Main(std::vector<String>& _UnknownArgs) = 0;
        virtual void OnUninitialize(void) = 0;

    private:
        int _Initialize(int _Argc, Char* _Argv[]);
        void _Uninitialize(void);
        void _ShowUsage(void);
        static void _SignalHandler(int _Signal);

        const Char* _Myname;
        std::vector<String> _Myarguemnts;
        Util::OptionSet _Myoptions;
        time_t _MyupTime;
        AtExit _MyatExit;
        static Application* _Myinstance;
        DISALLOW_COPY_AND_ASSIGN(Application);
    };

}}

#endif // UCOP_UTIL_APPLICATION_H_
